package com.yanyq.message.self;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class ZookeeperMessagePublisher implements Watcher {
//    private static CountDownLatch latch =  new CountDownLatch(1);
//    private static Stat stat = new Stat();
//    private static ZooKeeper zk =null;
    private final static Integer  SESSION_TIMEOUT = 5000;

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        String path  ="/message";
        String url = "127.0.0.1:2181";
        ZooKeeper zooKeeper = new ZooKeeper(url,SESSION_TIMEOUT,new ZookeeperMessagePublisher());
        if (zooKeeper.exists(path, false) == null) {
            zooKeeper.create(path, "测试消息发送".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        } else {
            zooKeeper.setData(path, "测试消息发送3".getBytes(),-1);
        }
        Thread.sleep(Long.MAX_VALUE);
        /*try {
//            String path  ="/publish";
            String path  ="/queue";
            zk =  new ZooKeeper("127.0.0.1:2181",SESSION_TIMEOUT,new ZookeeperMessagePublisher());
            latch.await();
            System.out.println("zk connection");
            byte[]  temp = zk.getData(path,true,stat);
            System.out.println("init data :pulish node data"+new String(temp));
            int i=0;
            while(true){
                System.out.println( "publish new Data:"+i);
                zk.setData(path,String.valueOf(i).getBytes(),-1);
                Thread.sleep(5000L);
                i++;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }*/

    }
    @Override
    public void process(WatchedEvent event) {
        System.out.println(">>::"+event.getType());
        /*if(Event.KeeperState.SyncConnected == event.getState()){
            System.out.println("receive watched event:"+event);
            System.out.println(event.getState());
            latch.countDown();
        }*/
    }
}
